import React from 'react';
import { connect } from 'react-redux'
import 'styles/component-lib/component-example.scss'
import { messages, deepCopy, uniquelizeArray } from "share/common"
import { Form, Modal, Spin, Affix, message, Button, Row, Col, Icon } from 'antd'
const ButtonGroup = Button.Group;
import 'styles/setting/workflow/new-workflow.scss'
//工作流画布
import SimpleFlow from 'components/simple-flow'
import { nodeTypes, approverNames } from "components/simple-flow/node-list";
//头部信息
import NewWorkflowHeader from 'containers/setting/new-workflow/detail/workflow-header'
import ErrorMessage from './comp/error-message'
//节点&条件设置
import NewWorkingSetting from 'containers/setting/new-workflow/workflow-setting'
import SlideFrame from 'components/slide-frame'
import workflowService from 'containers/setting/workflow/workflow.service'
import workflowUtil from 'containers/setting/new-workflow/utils'
import { chnNumChar, itineraryTypes } from 'containers/setting/new-workflow/utils'
import baseService from 'share/base.service'
//新版审批流接口
import newWorkflowService from 'containers/setting/new-workflow/new-workflow.service'
//redux
import { setWorkflowApproverType , setWorkflowRoleList} from "actions/cache";
import { setWorkflowScale } from "actions/cache";
class NewWorkflowDetail extends React.Component {
  constructor(props) {
    super(props);
    this.routerItem = [];
    let startOID = workflowUtil.getRandomUUID(), endOID = workflowUtil.getRandomUUID();
    this.ruleApprovalNodes = [
      {
        viewMap: {
          copySource: 'false',
          isCanPaste: 'false',
          errorToast: 'false',
        },
        type: nodeTypes.START,
        ruleApprovalNodeOID: startOID,
        remark: messages('setting.key1939')/*开始*/
      },
      {
        viewMap: {
          copySource: 'false',
          isCanPaste: 'false',
          errorToast: 'false',
        }, type: nodeTypes.END, ruleApprovalNodeOID: endOID, remark: messages('setting.key1252')/*结束*/
      }
    ];
    this.ruleRoutes = [
      { from: startOID, to: endOID }
    ];
    this.chainInfo = {
      approvalMode: 1005,
      formOID: props.formOID,
      ruleSceneOID: props.status === 'create' ? null : workflowUtil.getRandomUUID(),
      ruleApprovalNodes: this.ruleApprovalNodes,
      ruleApprovalRoutes: this.ruleRoutes,
    };
    this.state = {
      visible: false,
      ruleApprovalNodes: this.ruleApprovalNodes,
      ruleRoutes: this.ruleRoutes,
      routerItem: this.routerItem,
      //原始数据
      copyRuleRoutes: this.ruleRoutes,
      copyRouterItem: this.routerItem,
      copyRuleApprovalNodes: this.ruleApprovalNodes,
      //原始数据
      selectedNode: null,
      modelVisible: false,//配置弹框
      modelTitle: '',
      nowNode: {},//当前节点
      copyNowNode: {},
      tab: 'workflow',
      formOID: '',
      formInfo: {},//表单信息
      loading: false,
      chainInfo: this.chainInfo,
      showFormSetting: false, //是否显示表单配置
      chosenNodeType: null, //选中的节点
      chosenNodeWidget: {}, //选中的节点内容
      choseNodeIndex: 0, //选中节点的index
      formFieldList: null, //表单条件字段 用于更新字段的名称
      isRuleInEdit: false, //是否有审批条件处于编辑状态
      approveRuleModalVisible: false,
      errorLength: 0,
      errorList: [],
      copyChainInfo: {},
      //默认showValue
      expenseTypeObj: {},
      valueListObj: {},
      departmentListObj: {},
      costCenterListObj: {},
      companyListObj: {},
      entityListObj: {},
      userListObj: {},
      extendValueListObj: {},
      typeValueListObj: {},
      departmentPositionObj: {},
      invoiceLabelsObj: {},
      departmentGroupListObj: {},
      //默认showValue
      isSave: false,
      scale: 1,
      nowErrorNode: 0,
      errorListVisible: false,
      clientX: 0,//X轴滚动距离
      clientY: 0,//y轴滚动距离
      isChange: false,//节点是否变化
    };
  }

  componentDidMount() {
    this.setState({
      formOID: this.props.formOID,
    }, () => {
      this.setState({ loading: true }, () => {
        this.initData();
      });
    });
  }

  componentWillReceiveProps(nextProps) {
    if (this.state.formOID !== nextProps.formOID) {
      this.setState({
        formOID: nextProps.formOID
      }, () => {
        this.setState({ loading: true }, () => {
          this.initData();
        });
      })
    }
  }

  //获取表单信息
  getForm = () => {
    return workflowService.getCustomForm(this.state.formOID).then(res => {
      this.setState({ formInfo: res.data });
    })
  };

  //  valuedetail转换
  getStringJsonToObject = (value) => {
    workflowUtil.getStringJsonToObject(value)
  };

  //获取条件名称
  getDeaultShowValue = () => {
    Promise.all([
      this.getExpenseTypeList(),
      this.getBatchUserGroup(),
      this.getDepartmentList(),
      this.getCostCenterList(),
      this.getCompanyList(),
      this.getUserList(),
      this.getEntityList(),
      // this.getValueList(),//与下面这个判断重复了
      this.getTypeValueList(),
      this.getLocalList(),//获取本地的值列表默认值
      this.getLocalSpecialList(),
      this.getItineraryType(),
      this.getDepartmentExtend(),
      this.getLoanTypeList(),
      this.setDeparmentPosition(),
      this.getInvoiceLabels(),
      this.getDepartmentGroupValueList(),
    ]).then(() => {
      this.setConditionToOid();
      //有复制错误标示才进行校验
      if (this.state.chainInfo.warning) {
        if (!!this.verifyData().number) {
          this.setState({ errorListVisible: true })
        }
      }
      this.setState({ loading: false });
    })
  };


  //给编辑的custlist或者selector类型直接存的name的条件赋值conditionOID
  //所有不需要调接口的条件展示重新赋值
  setConditionToOid = () => {
    let { ruleApprovalNodes } = this.state;
    let remarkList = ['default_department_path', 'custom_form_department_path', 'default_credit_level'];
    ruleApprovalNodes.map(node => {
      if (node.type === nodeTypes.CONDITION) {
        let getCurrentPart = (items) => {
          for(let i = 0; i < items.length; i++) {
            let item = items[i];
            item.conditionOID = workflowUtil.getRandomUUID();
            if (item.type === 2) {//条件组
              getCurrentPart(item.ruleConditionDTOList);
            } else {
              if (remarkList.indexOf(item.remark) !== -1) {
                let showValue = {};
                !item.showValue && item.valueDetail && (JSON.parse(item.valueDetail)['value'] || []).map(name => {
                  showValue[name] = name;
                });
                item.showValue = showValue;
              }
            }
          }
        };
        getCurrentPart(node.ruleConditionDTO.ruleConditionDTOList);
      }
    });
    this.setState({ ruleApprovalNodes })
  };

  //获取已经选择的值
  getDefaultValuesOIDS = (remarkList, valueKey = 'value', contentTypeList = []) => {
    let list = [];
    let nodes = deepCopy(this.state.ruleApprovalNodes) || [];
    nodes.map(node => {
      if (node.type === nodeTypes.CONDITION) {
        node.ruleConditionDTO.ruleConditionDTOList && !!node.ruleConditionDTO.ruleConditionDTOList.length &&
        node.ruleConditionDTO.ruleConditionDTOList.map(item => {
          let type = workflowService.checkNewRemarkType(item.remark);
          let isShowAddBtn = !(String(item.symbol) === '9015' || String(item.symbol) === '9016');
          if (item.type === 2) {
            item.ruleConditionDTOList.map(sub => {
              let subType = workflowService.checkNewRemarkType(sub.remark);
              if (isShowAddBtn && (remarkList.indexOf(sub.remark) !== -1 || contentTypeList.indexOf(sub.fieldContent) !== -1)
                && subType !== 'combo') {
                sub.valueDetail && (JSON.parse(sub.valueDetail)[valueKey] || []).map(oid => {
                  list.push(oid)
                })
              }
              if (isShowAddBtn && subType === 'combo') {
                list.push(sub.field)
              }
            })
          } else {
            if (isShowAddBtn && (remarkList.indexOf(item.remark) !== -1 || contentTypeList.indexOf(item.fieldContent) !== -1)
              && type !== 'combo') {
              item.valueDetail && (JSON.parse(item.valueDetail)[valueKey] || []).map(oid => {
                list.push(oid)
              })
            }
            if (isShowAddBtn && type === 'combo') {
              list.push(item.field)
            }
          }
        });
      }
    });
    return list;
  };

  /**
   * showvalue赋值
   *list 存值数组
   *remarkList messagekey数组
   * valueKey 取valuedetai的值
   * */
  setShowValueToCondition = (obj, remarkList, valueKey = 'value', contentTypeList = []) => {
    let { ruleApprovalNodes } = this.state;
    ruleApprovalNodes.map(node => {
      if (node.type === nodeTypes.CONDITION) {
        node.ruleConditionDTO.ruleConditionDTOList && !!node.ruleConditionDTO.ruleConditionDTOList.length &&
        node.ruleConditionDTO.ruleConditionDTOList.map(item => {
          let type = workflowService.checkNewRemarkType(item.remark);
          let isShowAddBtn = !(String(item.symbol) === '9015' || String(item.symbol) === '9016');
          if (item.type === 2) {
            item.ruleConditionDTOList.map(sub => {
              let subType = workflowService.checkNewRemarkType(sub.remark);
              if (isShowAddBtn && (remarkList.indexOf(sub.remark) !== -1 || contentTypeList.indexOf(sub.fieldContent) !== -1)
                && subType !== 'combo') {
                let showValue = {};
                sub.valueDetail && (JSON.parse(sub.valueDetail)[valueKey] || []).map(oid => {
                  showValue[oid] = obj[oid];
                });
                sub.showValue = showValue;
              }
              if (isShowAddBtn && subType === 'combo') {
                if (obj[sub.field]) {
                  sub.showValue = obj[sub.field]
                }
              }
            })
          } else {
            if (isShowAddBtn && (remarkList.indexOf(item.remark) !== -1 || contentTypeList.indexOf(item.fieldContent) !== -1)
              &&  type !== 'combo') {
              let showValue = {};
              item.valueDetail && (JSON.parse(item.valueDetail)[valueKey] || []).map(oid => {
                showValue[oid] = obj[oid];
              });
              item.showValue = showValue;
            }
            if (isShowAddBtn &&  type === 'combo') {
              if (obj[item.field]) {
                item.showValue = obj[item.field]
              }
            }
          }
        });
      }
    });
    this.setState({ ruleApprovalNodes })
  };

  getBatchUserGroup = () => {
    let remarkList = ['default_user_group'];
    let valueOIDs = this.getDefaultValuesOIDS(remarkList, 'value');
    if (valueOIDs.length) {
      return newWorkflowService.getBatchUserGroup(valueOIDs).then(res => {
        let entityListObj = {};
        (res.data ? res.data : []).map(item => {
          entityListObj[item.userGroupOID] = item.name
        });
        this.setState({ entityListObj }, () => {
          this.setShowValueToCondition(entityListObj, remarkList, 'value');
        });
      })
    }
  };

  //获取费用类型列表
  getExpenseTypeList = () => {
    let remarkList = ['default_expense_type', 'default_each_one_expense_type_amount', 'default_expense_type_amount', 'default_average_amount'];
    let expenseTypeOID = this.getDefaultValuesOIDS(remarkList, 'value');
    let params = {
      formOID: this.props.formOID,
      isALL: true,
      subsidyType: 99
    };
    if (expenseTypeOID.length) {
      return baseService.getExpenseTypesByFormOIDV2(params).then(res => {
        this.setState({ expenseTypeList: res.data ? res.data.expenseTypes : [] });
        let expenseTypeObj = {};
        (res.data ? res.data.expenseTypes : []).map(item => {
          expenseTypeObj[item.expenseTypeOID] = item.name
        });
        this.setState({ expenseTypeObj }, () => {
          this.setShowValueToCondition(expenseTypeObj, remarkList, 'value')
        });
      })
    }
  };

  //获取费用标签
  getInvoiceLabels = () => {
    let remarkList = ['control_beyound_expense_label', 'control_beyound_label'];
    let valueOIDs = this.getDefaultValuesOIDS(remarkList, 'valueOIDs');
    if (valueOIDs.length) {
      return workflowService.getInvoiceLabels().then(res => {
        let invoiceLabelsObj = {};
        (res.data ? res.data : []).map(item => {
          invoiceLabelsObj[item.id] = item.name
        });
        this.setState({ invoiceLabelsObj }, () => {
          this.setShowValueToCondition(invoiceLabelsObj, remarkList, 'valueOIDs')
        })
      })
    }
  };

  getLocalList = () => {
    let remarkList = ['default_department_level', 'custom_form_department_level'];
    let oids = this.getDefaultValuesOIDS(remarkList, 'value');
    let oidsObj = {};
    (oids || []).map(id => {
      oidsObj[id] = chnNumChar[Number(id) - 1];
    });
    this.setState({ oidsObj }, () => {
      this.setShowValueToCondition(oidsObj, remarkList, 'value')
    });

  };

  getItineraryType = () => {
    let remarkList = ['default_stroke_type'];
    let oids = this.getDefaultValuesOIDS(remarkList, 'value');
    let oidsObj = {};
    (oids || []).map(id => {
      //本地行程数据
      itineraryTypes.map(type => {
        if (type.id === Number(id)) {
          oidsObj[id] = type.name
        }
      })
    });
    this.setState({ oidsObj }, () => {
      this.setShowValueToCondition(oidsObj, remarkList, 'value')
    });
  }

  getLocalSpecialList =()=>{
    let remarkList =['default_auto_audit_result']
    let oidsObj ={
      '0':messages('setting.key2240')/*未自动审核*/,
      '1':messages('common.pass')/*通过*/,
      '2':messages('setting.key2241')/*不通过*/,

    }
    this.setState({ oidsObj }, () => {
      this.setShowValueToCondition(oidsObj, remarkList, 'value')
    });
  }

  //获取部门列表
  getDepartmentList = () => {
    let remarkList = ['select_department', 'default_user_department'];
    let departmentOID = this.getDefaultValuesOIDS(remarkList, 'value');
    if (departmentOID.length) {
      return workflowService.getDepartmentSimpleList(departmentOID).then(res => {
        let departmentListObj = {};
        (res.data ? res.data : []).map(item => {
          departmentListObj[item.departmentOID] = item.name
        });
        this.setState({ departmentListObj }, () => {
          this.setShowValueToCondition(departmentListObj, remarkList, 'value');
        });
      })
    }
  };

  //获取成本中心列表
  getCostCenterList = () => {
    let remarkList = ['select_cost_center'];
    let costCenterOID = this.getDefaultValuesOIDS(remarkList, 'value');
    if (costCenterOID.length) {
      return workflowService.getBatchCostCenterList(costCenterOID).then(res => {
        this.setState({ costCenterList: res.data });
        let costCenterListObj = {};
        (res.data ? res.data : []).map(item => {
          costCenterListObj[item.costCenterItemOID] = item.name
        });
        this.setState({ costCenterListObj }, () => {
          this.setShowValueToCondition(costCenterListObj, remarkList, 'value');
        });
      })
    }
  };

  //获取公司列表
  getCompanyList = () => {
    let remarkList = ['default_applicant_company', 'select_company'];
    let companyOID = this.getDefaultValuesOIDS(remarkList, 'value')
    if (companyOID.length) {
      return workflowService.getBatchCompanyItemList(companyOID).then(res => {
        let companyListObj = {};
        (res.data ? res.data : []).map(item => {
          companyListObj[item.companyOID] = item.name
        });
        this.setState({ companyListObj }, () => {
          this.setShowValueToCondition(companyListObj, remarkList, 'value');
        });
      })
    }
  };

  //获取人员列表
  getUserList = () => {
    let remarkList = ['default_user_direct_leadership', 'default_user_applicant'];
    let userOIDs = this.getDefaultValuesOIDS(remarkList, 'value');
    if (userOIDs.length) {
       return workflowService.getBatchUsers(userOIDs).then(res => {
          let userListObj = {};
          (res.data ? res.data : []).map(item => {
            userListObj[item.userOID] = item.fullName
          });
          this.setState({ userListObj }, () => {
            this.setShowValueToCondition(userListObj, remarkList, 'value');
          });
        })
    }
  };

  //获取部门组
  getDepartmentGroupValueList = () => {
    let remarkList = ['default_department_group', 'custom_form_department_group'];
    let departmentGroupListOID = this.getDefaultValuesOIDS(remarkList, 'value');
    if (departmentGroupListOID.length) {
      return workflowService.getDepartmentGroupList(departmentGroupListOID).then(res => {
        let departmentGroupListObj = {};
        (res.data ? res.data : []).map(item => {
          departmentGroupListObj[item.deptGroupCode] = item.name
        });
        this.setState({ departmentGroupListObj }, () => {
          this.setShowValueToCondition(departmentGroupListObj, remarkList, 'value');
        });
      })
    }
  };

  //获取法人实体列表
  getEntityList = () => {
    let remarkList = ['select_corporation_entity', 'default_corporation_entity'];
    let entityOID = this.getDefaultValuesOIDS(remarkList, 'value')
    if (entityOID.length) {
      return workflowService.getBatchCorporationEntityList(entityOID).then(res => {
        let entityListObj = {};
        (res.data ? res.data : []).map(item => {
          entityListObj[item.companyOID] = item.name
        });
        this.setState({ entityListObj }, () => {
          this.setShowValueToCondition(entityListObj, remarkList, 'value');
        });
      })
    }
  };

  //获取全部部门扩展字段值列表
  getDepartmentExtend = () => {
    let remarkList = ['default_user_department_extend', 'custom_form_department_extend', 'cust_list'];
    let valueListOID = this.getDefaultValuesOIDS(remarkList, 'valueOIDs');
    if (valueListOID.length) {
      return workflowService.getCustomEnumerationList(valueListOID).then(res => {
        let extendValueListObj = {};
        (res.data ? res.data : []).map(item => {
          extendValueListObj[item.customEnumerationItemOID] = item.messageKey
        });
        this.setState({ extendValueListObj }, () => {
          this.setShowValueToCondition(extendValueListObj, remarkList, 'valueOIDs');
        });
      })
    }
  };

  //获取借款类型值列表
  getLoanTypeList = () => {
    let remarkList = ['default_loan_type'];
    let valueListOID = this.getDefaultValuesOIDS(remarkList, 'value');
    if (valueListOID.length) {
      return workflowService.getLoanTypeList({
        setOfBookId: this.props.tenantMode ?
          this.props.setOfBooksId : this.props.company.setOfBooksId
      }).then(res => {
        let loanTypeListObj = {};
        (res.data ? res.data : []).map(item => {
          loanTypeListObj[item.id] = item.description
        });
        this.setState({ loanTypeListObj }, () => {
          this.setShowValueToCondition(loanTypeListObj, remarkList, 'valueOIDs')
        });
      })
    }
  };

  //根据type获取值列表
  getTypeValueList = () => {
    let fieldContent = ['1001', '1007', '1008', '1002'];//自定义值列表
    let typeValueListOID = this.getDefaultValuesOIDS([], 'valueOIDs', fieldContent);
    if (typeValueListOID.length) {
      return workflowService.getCustomEnumerationList(typeValueListOID).then(res => {
        this.setState({ typeValueList: res.data });
        let typeValueListObj = {};
        (res.data ? res.data : []).map(item => {
          typeValueListObj[item.customEnumerationItemOID] = item.messageKey;
        });
        this.setState({ typeValueListObj }, () => {
          this.setShowValueToCondition(typeValueListObj, [], 'valueOIDs', fieldContent);
        });
      })
    }
  };

  //获取审批链详情
  getApprovalChain = () => {
    let { status } = this.props;
    if (status === 'create') {
      this.setState({
        chainInfo: this.chainInfo,
        ruleApprovalNodes: this.ruleApprovalNodes,
        ruleRoutes: this.ruleRoutes,
        copyChainInfo: this.chainInfo,
        copyRuleRoutes: this.ruleRoutes,
        copyRuleApprovalNodes: this.ruleApprovalNodes,
        errorList: [],
      })
    } else {
      return newWorkflowService.postWorkflowDetail({
        booksID: this.props.setOfBooksId,
        formOID: this.state.formOID,
        version: this.props.version
      }).then(res => {
        let data = workflowUtil.modifyFlowData(res.data);
        this.setState({
          chainInfo: data,
          copyChainInfo: JSON.parse(JSON.stringify(data)),
          ruleRoutes: data.ruleApprovalRoutes,
          copyRuleRoutes: JSON.parse(JSON.stringify(data.ruleApprovalRoutes)),
          copyRuleApprovalNodes: JSON.parse(JSON.stringify(data.ruleApprovalNodes)),
          ruleApprovalNodes: data.ruleApprovalNodes,
        });
      });
    }
  };

  //获取数据 初始化数据
  initData = () => {
    this.routerItem = [
      {
        name: '审批流',
        type: 'workflow',
        default: true,
      },
      {
        name: '表单配置',
        type: 'formSetting',
        default: false,
      }
    ];
    workflowService.getFormFields(this.state.formOID, '1.0').then(res => {
      this.setState({ formFieldList: workflowUtil.setMarkOiDtoField(res.data) }, () => {
        Promise.all([
          this.getForm(),
          this.getApprovalChain(),
          this.getApproverType(),
          this.getRoleList()
        ]).then(() => {
          this.getDeaultShowValue();
        });
      });
    }).catch(() => {
      this.setState({ loading: false });
      message.error(messages('common.error1'));
    });
  };

  getApproverType = () => {
    return newWorkflowService.getApproverType().then(res => {
      this.props.dispatch(setWorkflowApproverType(res.data));
    })
  };

  getRoleList = () => {
    return newWorkflowService.getRoleList().then(res => {
      this.props.dispatch(setWorkflowRoleList(res.data));
    })
  }

  setDeparmentPosition = () => {
    let remarkList = ['default_department_role', 'custom_form_department_role'];
    let { workflowDepartmentPosition } = this.props;
    let valueListOID = this.getDefaultValuesOIDS(remarkList, 'value');
    if (valueListOID.length) {
      let departmentPositionObj = {};
      (workflowDepartmentPosition && JSON.stringify(workflowDepartmentPosition) !== '{}' ? workflowDepartmentPosition : []).map(item => {
        // item.i18n && item.i18n.positionName && item.i18n.positionName.map(nameItem => {
        //   nameItem.language === this.props.language.code && (departmentPositionObj[item.positionCode] = nameItem.value)
        // })
        departmentPositionObj[item.positionCode] = item.positionName
      });
      this.setState({ departmentPositionObj }, () => {
        this.setShowValueToCondition(departmentPositionObj, remarkList, 'value');
      });
    }
  }

  handleChange = (ruleApprovalNodes, ruleRoutes) => {
    let { chainInfo } = this.state;
    let canPasteTypeList = [];
    ruleApprovalNodes.map(item => {
      //复制赋值
      if (item.copySource) {
        uniquelizeArray(canPasteTypeList.push(item.type));
      }
    });
    chainInfo.ruleApprovalNodes = workflowUtil.getNodeMessage(ruleApprovalNodes, canPasteTypeList);
    chainInfo.ruleApprovalRoutes = ruleRoutes;
    this.setState({ chainInfo, ruleApprovalNodes, ruleRoutes }, () => {
      if (chainInfo.warning) {
        this.verifyData()
      }
    });
  };

  handleSelectNode = node => {
    let { ruleApprovalNodes, formInfo, errorList } = this.state;
    let { readOnly } = this.props;
    if (readOnly) {
      this.setState({ selectedNode: node });
      return;
    }
    if (node) {
      let nowNode = ruleApprovalNodes.find(item => item.ruleApprovalNodeOID === node);
      if (nowNode) {
        if (!nowNode.viewMap) {
          nowNode.viewMap = {
            copySource: 'false',
            isCanPaste: 'false',
            errorToast: 'false',
          };
        }
        if (!nowNode.warning && nowNode.type !== nodeTypes.CONDITION) {
          nowNode.viewMap.errorToast = 'false';
        }
        //只有报销单的打印节点可配置
        if (nowNode.type === 1005 &&
          formInfo.formType && (String(formInfo.formType).charAt(0) === '3'
          || formInfo.formType === 2005)) {
          this.setState({
            selectedNode: node,
            nowNode,
            copyNowNode: deepCopy(nowNode),
            modelVisible: true,
          });
          return;
        } else if (nowNode.type !== 1005) {
          this.setState({
            selectedNode: node,
            nowNode,
            copyNowNode: deepCopy(nowNode),
            modelVisible: true,
          })
        }
        !!errorList.length && errorList.map((item, index) => {
          if (item.id === nowNode.ruleApprovalNodeOID) {
            errorList.splice(index, 1);
          }
        });
        this.setState({
          errorList
        })
      }
    }
  };

  afterClose = e => {
    let { chainInfo } = this.state;
    if (e) {
      chainInfo.ruleApprovalNodes.map((item, index) => {
        if (item.ruleApprovalNodeOID === e.ruleApprovalNodeOID) {
          chainInfo.ruleApprovalNodes.splice(index, 1, e);
        }
      });
      this.setState({
        chainInfo,
        modelVisible: false,
        ruleApprovalNodes: chainInfo.ruleApprovalNodes,
        ruleRoutes: chainInfo.ruleApprovalRoutes
      })
    } else {
      this.setState({
        nowNode: this.state.copyNowNode,
      })
    }
    if(this.state.nowNode.type === nodeTypes.CONDITION){
      this.verifyData();
    }
    this.setState({ isChange: false });
    if (JSON.stringify(this.state.nowNode) !== JSON.stringify(this.state.copyNowNode)) {
      this.setState({ isChange: true });
    } else {
      this.setState({ isChange: false });
    }
  };
  handleSelectTab = val => {
    let { tab, copyRuleApprovalNodes, copyRuleRoutes } = this.state;
    if (tab === 'workflow' && val.type === 'formSetting') {
      Modal.confirm({
        title: messages('components.key464')/*提示*/,
        content: messages('setting.key1902')/*切换菜单会清空当前菜单的操作，是否继续？*/,
        onOk: () => {
          //关闭全屏恢复原始数据
          this.setState({
            ruleApprovalNodes: copyRuleApprovalNodes,
            ruleRoutes: copyRuleRoutes,
            tab: val.type
          });
        },
        onCancel: () => {
          this.setState({
            routerItem: this.routerItem
          })
        }
      });
    } else {
      this.setState({ tab: val.type, })
    }
  };

  verifyData = () => {
    let { chainInfo, errorList } = this.state;
    let errorLengths = 0, flag = true;
    errorList = [];
    chainInfo.formOID = this.state.formOID;
    chainInfo.warning = false;
    //拿出同一层级的条件进行对比
    let saveRuleApprovalRoutes = this.modifyFlowDataToSave(chainInfo).ruleApprovalRoutes;//已经将条件节点变为路由的数据 方便计算层级关系
    let sourceOIDs = [], saveConditionRoute = [], sameSourceOIDConOIDs = [], sameLevelNodes = [], errorConditionLevels = [];
    saveRuleApprovalRoutes.map(route => {
      if (route.ruleConditionDTO) {
        saveConditionRoute.push(route);//条件路由数组
        if (sourceOIDs.indexOf(route.sourceNodeOID) === -1) {//去重
          sourceOIDs.push(route.sourceNodeOID);//来源路由OID
        }
      }
    });
    sourceOIDs.map(sourceOID => {
      sameLevelNodes = [];
      sameSourceOIDConOIDs = [];
      saveConditionRoute.map(route => {
        if (sourceOID === route.sourceNodeOID) {
          sameSourceOIDConOIDs.push(route.ruleApprovalRouteOID);//同一路由OID的条件路由oid数组
        }
      });
      chainInfo.ruleApprovalNodes.map(node => {
        if (node.type === nodeTypes.CONDITION) {
          sameSourceOIDConOIDs.map(nodeOID => {
            if (nodeOID === node.ruleApprovalNodeOID) {
              sameLevelNodes.push(node);//相同节点的来源路由的条件节点数据数组
            }
          })
        }
      });
      //用来往errorList中塞入错误的提示 每一个层级塞入一个判断 只有最后一个条件可以为空
      sameLevelNodes.map(item => {
        if (item.priority !== sameLevelNodes.length && item.ruleConditionDTO.ruleConditionDTOList.length === 0) {
          errorConditionLevels.push(item);
        }
      });
    });
    //拿出同一层级的条件进行对比
    chainInfo.ruleApprovalNodes.map(node => {
      if (!node.viewMap) {
        node.viewMap = {
          copySource: 'false',
          isCanPaste: 'false',
          errorToast: 'false',
        };
      }
      node.viewMap.errorToast = 'false';
      if (node.type === nodeTypes.APPROVE || node.type === nodeTypes.KNOWN) {
        //审批人未设置
        if (!workflowUtil.isHaveApporver(node.ruleBranchApprover)) {
          node.viewMap.errorToast = 'true';
          errorList.push({
            message: messages('setting.key1903', { arg1: node.remark })/*{arg1}未设置*/,
            id: node.ruleApprovalNodeOID
          });
          errorLengths++;
        }
      }
      if (node.type === nodeTypes.BOT) {
        node.ruleBranchApprover =
          {
            '7700': [{
              approverEntityOID: "00000000-0000-0000-0000-000000000000",
              approverType: 1003,
              level: 1,
              ruleApprovalNodeOID: node.ruleApprovalNodeOID,
              ruleApproverOID: workflowUtil.getRandomUUID(),
              status: 1
            }],
            '1000': [],
            '1002': [],
            '6001': [],
            '6002': [],
            '6004': [],
            '6100': [],
            '6003': [],
            '6005': [],
            '6006': [],
            '1004': [],
          }
      }
      if (node.type === nodeTypes.CREDIT) {
        node.ruleBranchApprover = {
          '7700': [{
            "approverEntityOID": "00000000-0000-0000-0000-000000000002",
            "approverType": 1007,
            "level": 1,
            "name": "信用付款",
            "remark": "信用付款",
            "ruleApprovalNodeOID": node.ruleApprovalNodeOID,
            "ruleApproverOID": workflowUtil.getRandomUUID(),
            "status": 1
          }],
          '1000': [],
          '1002': [],
          '6001': [],
          '6002': [],
          '6004': [],
          '6100': [],
          '6003': [],
          '6005': [],
          '6006': [],
          '1004': [],
        }
      }
      //条件未设置
      if (node.type === nodeTypes.CONDITION) {
        //errorConditionLevels 每个层级只有最后一个条件可以为空
        errorConditionLevels.map(item => {
          if (node.ruleApprovalNodeOID === item.ruleApprovalNodeOID) {
            node.viewMap.errorToast = 'true';
            errorList.push({
              message: messages('setting.key1903', { arg1: node.remark })/*{arg1}未设置*/,
              id: item.ruleApprovalNodeOID,//定位到该层第一个元素
            });
            errorLengths++;
          }
        });
        if (!node.ruleConditionDTO) {
          node.viewMap.errorToast = 'true';
          errorList.push({
            message: messages('setting.key1903', { arg1: node.remark })/*{arg1}未设置*/,
            id: node.ruleApprovalNodeOID
          });
          errorLengths++;
        } else {
          //校验条件必填 返回true为可以保存
          if (!workflowUtil.handleVerify(node.ruleConditionDTO, node).isValid) {
            node.viewMap.errorToast = 'true';
            errorList.push({
              message: workflowUtil.handleVerify(node.ruleConditionDTO, node).mess,
              id: node.ruleApprovalNodeOID
            });
            errorLengths++;
          }
        }
      } else {
        //复制异常情况处理
        if (node.warning) {
          node.viewMap.errorToast = 'true';
          errorList.push({
            message: messages('setting.key2004',{arg1:node.remark})/*{arg1}，审批流不支持该节点*/,
            id: node.ruleApprovalNodeOID
          });
          chainInfo.warning = true;
          errorLengths++;
        }
      }

    });

    if (errorLengths > 0) {
      flag = false;
      // return;
    }
    this.setState({ errorLength: errorLengths, errorList });
    return { number: errorLengths, list: errorList };
  };

  scrollTo = elem => {
    if (elem) {
      elem.scrollIntoViewIfNeeded();
    }
    this.setState({ errorListVisible: true, })
  };

  handleNextError = num => {
    let { errorList } = this.state;
    if (num === -1 || num === errorList.length) {
      return
    }
    this.setState({
      nowErrorNode: num,
    }, () => {
      this.scrollTo(document.getElementById(`flow-node-${errorList[num].id}`))
    })
  };

  handleSave = e => {
    if (this.props.readOnly) {
      if (!this.state.selectedNode) {
        message.error(messages('setting.key2014')/*请选择一个节点进行跳转*/);
        return;
      } else {
        this.setState({ loading: true });
        this.props.onSuccess(this.state.selectedNode);
      }
      // this.props.onSuccess(this.state.selectedNode);
      return
    }
    let { chainInfo, errorLength } = this.state;
    if (!e) {
      message.error(messages('setting.key2005')/*请填写工作流名称*/);
      return
    }
    chainInfo.name = e;
    this.setState({ chainInfo }, () => {
      let verifyData = this.verifyData();
      if (!!verifyData.number) {
        this.setState({ isChange: false });
        Modal.error({
          title: messages('setting.key1963')/*当前设置无法保存*/,
          content: messages('setting.key1964', { arg1: verifyData.number })/*共{arg1}条内容需完善，请根据页面提示操作*/,
          onOk: () => {
            this.setState({
              chainInfo,
              errorLength,
              isChange: true,
              errorList: verifyData.list,
              modelVisible: false,
              nowErrorNode: 0,
              ruleApprovalNodes: chainInfo.ruleApprovalNodes,
              ruleRoutes: chainInfo.ruleApprovalRoutes
            });
            this.scrollTo(document.getElementById(`flow-node-${verifyData.list[0].id}`))
          },
        });
      } else {
        if (this.props.status === 'create') {
          this.handleOk()
        } else {
          this.setState({ confirmVisible: true })
        }
      }
    });
  };

  modifyFlowDataToSave = (data) => {
    return workflowUtil.modifyFlowDataToSave(JSON.parse(JSON.stringify(data)))
  };

  //发布新版本
  handleOk = () => {
    let { chainInfo, errorLength } = this.state;
    this.setState({ loading: true });
    chainInfo.booksID = this.props.setOfBooksId;
    newWorkflowService.postSaveNewVersion(this.modifyFlowDataToSave(chainInfo))
      .then(res => {
        message.success(messages('setting.key211')/*保存成功*/);
        this.setState({ loading: false, isSave: true })
        this.props.onSuccess(this.state.formOID);
      })
      .catch(err => {
        if (err.response && err.response.data) {
          message.error(err.response.data.message);
        }
        this.setState({ loading: false })
      })
  };

  handleSubimt = () => {
    let { chainInfo } = this.state;
    this.setState({ errorList: [] }, () => {
      this.setState({ loading: true });
      chainInfo.booksID = this.props.setOfBooksId;
      newWorkflowService.postSaveVersion(workflowUtil.modifyFlowDataToSave(JSON.parse(JSON.stringify(chainInfo))))
        .then(res => {
          message.success(messages('setting.key211')/*保存成功*/);
          this.setState({ loading: false, isSave: true });
          this.props.onSuccess(this.state.formOID);
        })
        .catch(err => {
          if (err.response && err.response.data) {
            message.error(err.response.data.message);
          }
          this.setState({ loading: false })
        })
    })
  };

  handleCancel = () => {
    this.setState({ confirmVisible: false });
  };

  handleChangeVisible = () => {
    this.props.onSuccess(false);
  };

  handleCloseErrorList = () => {
    this.setState({ errorListVisible: false })
  };

  handleScale = type => {
    let { scale } = this.state;
    if (type === 'less') {
      scale = scale - 0.25;
    } else {
      scale = scale + 0.25;
    }
    this.setState({
      scale
    });
  };

  drag = ev => {
    if (!this.props.readOnly) {
      return
    }
    let disX = ev.pageX - this.state.clientX;
    let disY = ev.pageY - this.state.clientY;
    document.onmousemove = ev => {
      this.setState({
        clientX: Number(ev.pageX) - Number(disX),
        clientY: Number(ev.pageY) - Number(disY)
      });
    };
    document.onmouseup = () => {
      document.onmousemove = null;
      document.onmousedown = null;
    }
  };

  handleChangeName = (name) => {
    let { chainInfo } = this.state;
    chainInfo.name = name;
    this.setState({ chainInfo })
  }

  render() {
    const {
      scale, confirmVisible, errorList, nowErrorNode, errorListVisible, ruleApprovalNodes, ruleRoutes, selectedNode, routerItem,
      modelVisible, nowNode, formInfo, loading, formFieldList, chainInfo, clientY, clientX, isChange
    } = this.state;
    const { readOnly, currentNodeOID } = this.props;
    return (
      <Affix className="new-workflow">
        <Spin spinning={loading}>
          <NewWorkflowHeader
            routerItem={routerItem}
            onSave={ e => {this.handleSave(e)}}
            name={chainInfo.name || formInfo.formName}
            version={this.props.version}
            readOnly={readOnly}
            onChangeName={ name =>{this.handleChangeName(name)}}
            onCancel={this.props.onCancel}
            onSelectTab={val => this.handleSelectTab(val)}
            onClose={() => this.handleChangeVisible(false)}
          />
          <Modal
            visible={confirmVisible}
            title={messages('setting.key1965')/*保存流程*/}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            footer={[
              <Button key="save" type="primary" loading={loading}
                      onClick={this.handleSubimt}>{messages('setting.key1079')/*保存*/}</Button>,
              <Button key="submit" type="primary" loading={loading}
                      onClick={this.handleOk}> {messages('setting.key1966')/*另存*/}
              </Button>,

              <Button key="cancel" onClick={this.handleCancel}> {messages('setting.key1080')/*取消*/}
              </Button>,
            ]}
          >
            <div>{messages('setting.key1967')/*直接保存或另存为新版本*/}</div>
          </Modal>
          {errorList.length > 0 &&
          <div className="error-panel slideUp" onClick={() => this.setState({ errorListVisible: true })}>
            <Icon style={{ color: 'red' }}
                  type="exclamation-circle"/> {messages('setting.key1905', { arg1: errorList.length })/*错误提示({arg1})*/}
          </div>
          }
          {errorList.length > 0 && errorListVisible &&
          <ErrorMessage
            errorList={errorList}
            nowErrorNode={nowErrorNode}
            onCloseErrorList={this.handleCloseErrorList}
            onNextError={this.handleNextError}
          />
          }
          <div className="affix-btn">
            <ButtonGroup size="small">
              <Button disabled={scale === 0.5} onClick={() => this.handleScale('less')}>
                <Icon type="minus"/>
              </Button>
              <Button disabled>{scale * 100}%</Button>
              <Button disabled={scale === 1.5} onClick={() => this.handleScale('more')}>
                <Icon type="plus"/>
              </Button>
            </ButtonGroup>
          </div>
          {!loading && this.props.nodeList.length !== 0 &&
          <div
            id="simple-flow-wrap"
            style={{ height: document.body.clientHeight - 64, }}
            onMouseDown={this.drag.bind(this)}>
            <SimpleFlow
              currentNodeOID={currentNodeOID}
              valueKey="ruleApprovalNodeOID"
              showValueKey="remark"
              routes={ruleRoutes}
              scale={scale}
              clientY={clientY}
              clientX={clientX}
              readOnly={readOnly}
              nodeList={this.props.nodeList}
              nodes={ruleApprovalNodes}
              isChange={isChange}
              selectedNode={selectedNode}
              onSelectNode={this.handleSelectNode}
              onChange={this.handleChange}
            />
          </div>}
          <SlideFrame
            content={NewWorkingSetting}
            title={`${nowNode.remark || messages('setting.key1330')/*条件*/ + nowNode.priority}${messages('setting.key1906')/*设置*/}`}
            width={'50%'}
            params={{
              ruleApprovalNodes,
              nowNode, formFieldList, ruleRoutes, formInfo, chainInfo,
              setOfBooksId: this.props.setOfBooksId
            }}
            hasFooter
            show={modelVisible}
            afterClose={this.afterClose}
            onClose={() => { this.setState({ modelVisible: false }); }}
          />
        </Spin>
      </Affix>
    )
  }
}

NewWorkflowDetail.PropTypes = {
  example: React.PropTypes.object.isRequired,
  componentKey: React.PropTypes.string.isRequired,
  formOID: React.PropTypes.string.isRequired,
  setOfBooksId: React.PropTypes.string,
  currentNodeOID: React.PropTypes.string,
  version: React.PropTypes.string,
  title: React.PropTypes.string,
  nodeList: React.PropTypes.array,
  readOnly: React.PropTypes.boolean,//跳转 新建模式
  status: React.PropTypes.string,//create新建
  onSuccess: React.PropTypes.func,//成功发布回调
  onCancel: React.PropTypes.func
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    language: state.main.language,
    workflowDepartmentPosition: state.cache.workflowDepartmentPosition,
  }
}

const WrappedNewWorkflowDetail = Form.create()(NewWorkflowDetail);

export default connect(mapStateToProps)(WrappedNewWorkflowDetail);
